#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的权限模型
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, JSON
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.core.database import Base

class User(Base):
    __tablename__ = "users"
    __table_args__ = {'extend_existing': True}
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False, comment="用户名")
    password = Column(String(255), nullable=False, comment="密码（加密存储）")
    name = Column(String(100), nullable=False, comment="真实姓名")
    role_id = Column(Integer, ForeignKey("roles.id"), nullable=False, comment="角色ID")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联
    role = relationship("Role", back_populates="users")
    
    def to_dict(self):
        return {
            "id": self.id,
            "username": self.username,
            "name": self.name,
            "role_id": self.role_id,
            "role_name": self.role.name if self.role else None,
            "is_active": self.is_active,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }

class Role(Base):
    __tablename__ = "roles"
    __table_args__ = {'extend_existing': True}
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, nullable=False, comment="角色名称")
    menu_permissions = Column(String(500), default='', comment="菜单权限列表(逗号分隔的菜单key)")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联
    users = relationship("User", back_populates="role")
    
    def to_dict(self):
        # 将逗号分隔的字符串转换为列表
        if self.menu_permissions:
            menu_permissions = [p.strip() for p in str(self.menu_permissions).split(',') if p.strip()]
        else:
            menu_permissions = []
        
        return {
            "id": self.id,
            "name": self.name,
            "menu_permissions": menu_permissions,
            "is_active": self.is_active,
            "created_at": self.created_at.isoformat() if self.created_at else None
        }